import { login } from "@/api/user/login";
export default {
  // 命名空间必写，防止模块之间互相影响
  namespaced: true,
  state: () => ({
    isLogin: uni.getStorageSync("isLogin") || false,
    userInfo: uni.getStorageSync("userInfo") || {},
    token: uni.getStorageSync("token") || "",
  }),
  mutations: {
    setLogin(state, data) {
      uni.setStorageSync("isLogin", data);
      state.isLogin = data;
    },
    setUserInfo(state, data) {
      uni.setStorageSync("userInfo", data);
      state.userInfo = data;
    },
    setToken(state, data) {
      uni.setStorageSync("token", data);
      state.token = data;
    },
  },
  actions: {
    // 登录
    async login({ commit }, data) {
      const res = await login(data);
      if (res.code !== 200) return;
      commit("setLogin", true);
      commit("setUserInfo", res.data.userInfo);
      commit("setToken", res.data.token);
      return res;
    },
    // 退出登录
    logout({ commit }) {
      commit("setLogin", false);
      commit("setUserInfo", "");
      commit("setToken", "");
      return Promise.resolve({
        code: 200,
        msg: "退出成功",
      });
    },
  },
  getters: {
    isLogin: (state) => state.isLogin,
    userInfo: (state) => state.userInfo,
    token: (state) => state.token,
  },
};
